package com.goktech.commons.excel;

import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.goktech.commons.excel.utils.ValueSelector;
import com.goktech.commons.utils.StringUtils;
import com.goktech.commons.utils.TagUtils;

/**
 * @author 24252
 *
 */
public class RowFactory extends AbstractRow {

	private final static Logger logger = LoggerFactory.getLogger(RowFactory.class);

	private Map<String, Object> data;

	private ExcelStyle excelStyle;

	public RowFactory(Rows rows, Sheet sheet, Workbook workbook) {
		super(rows, sheet, workbook);
	}

	public void setExcelStyle(ExcelStyle excelStyle) {
		this.excelStyle = excelStyle;
	}

	public RowFactory(Rows rows, Sheet sheet, Workbook workbook, Map<String, Object> data) {
		super(rows, sheet, workbook);
		this.data = data;
	}

	public RowFactory create(HSSFWorkbook workbook) {
		Row[] rowArray = rows.rows();
		return this;
	}

	@Override
	public void create() {
		if (rows == null) {
			logger.warn("rows is null ,RowFactory stoped");
			return;
		}
		Row[] rowArray = rows.rows();
		for (Row row : rowArray) {
			Cell[] cellArray = row.cells();
			//创建行，如果已经表明行的位置，将会取行的位置，否则将以本类的索引为准
			int rowIndex = TagUtils.getInteger(row.rowIndex(),data) == -1?this.maxIndex:TagUtils.getInteger(row.rowIndex(),data);
			org.apache.poi.ss.usermodel.Row erow = this.createRow(rowIndex);
			//确定行宽是否设置
			int height = TagUtils.getInteger(row.height(), data);
			if(height != -1){
				erow.setHeight((short)height);
			}
			float heightInPoints = TagUtils.getFloat(row.heightInPoints(), data);
			if(heightInPoints != -1){
				erow.setHeightInPoints(heightInPoints);
			}
			for(Cell cell : cellArray){
				int cellWidth = TagUtils.getInteger(cell.width(), data);
				int cellheight = TagUtils.getInteger(cell.height(), data);
				int cellIndex = TagUtils.getInteger(cell.idnex(), data);
				org.apache.poi.ss.usermodel.Cell ecell = this.createCell(erow, TagUtils.getInteger(cell.idnex(),data));
				CellRangeAddress cra = null;
				//判断是否需要合并单元格
				if(cellWidth != -1 || cellheight != -1){
					cra = new CellRangeAddress(rowIndex, cellheight == -1 ? rowIndex : rowIndex + cellheight, 
							cellIndex, cellWidth == -1 ? cellIndex : cellIndex + cellWidth);
					this.sheet.addMergedRegion(cra);//合并单元格
					if(logger.isDebugEnabled()){
						logger.debug("当前合并单元格的位置为:{}-{}-{},{}",cra.getFirstRow(),cra.getLastRow(),cra.getFirstColumn(),cra.getLastColumn());
					}
					setRowIndex(cra.getLastRow());
				}
				setValue(cell,ecell,data);
				if (excelStyle != null) {
					ecell.setCellStyle(StringUtils.isEmpty(cell.style().id()) ? excelStyle.getStyle(cell.style()) : excelStyle.getStyle(cell.style().id()));
				}
				//合并 单元格的样式和单元格保持一致
				if(cra != null){
					synchroStyle(ecell.getCellStyle(),cra,sheet,workbook);
				}
				
			}
			if(this.maxIndex < rowIndex){
				setRowIndex(rowIndex);
			}
		}
	}
	
	/**
	 * 为单元格设置值，这里会判断传入的map是否为空
	 */
	private void setValue(Cell cell,org.apache.poi.ss.usermodel.Cell ecell,Map<String,Object> data){
		if (data == null) {
			ecell.setCellValue(cell.value());
			CellStyle cellStyle = workbook.createCellStyle();
			ecell.setCellStyle(cellStyle);
		} else {
			String key = TagUtils.getKey(cell.value());
			if (key == null) {
				ecell.setCellValue(cell.value());
			} else {
				ValueSelector.getValue(TagUtils.replace(cell.value(), data), ecell, cell);
			}
		}
	}
	
	/*
	 * 给合并的单元格设置默认的样式
	 */
	public static void synchroStyle(CellStyle style,CellRangeAddress cra,Sheet sheet,
			Workbook workbook){
		RegionUtil.setBorderBottom(style.getBorderBottom(), cra, sheet,workbook); // 下边框  
        RegionUtil.setBorderLeft(style.getBorderLeft(), cra, sheet,workbook); // 左边框  
        RegionUtil.setBorderRight(style.getBorderRight(), cra, sheet,workbook); // 有边框  
        RegionUtil.setBorderTop(style.getBorderTop(), cra, sheet,workbook);
        RegionUtil.setBottomBorderColor(style.getBottomBorderColor(), cra, sheet, workbook);
        RegionUtil.setTopBorderColor(style.getTopBorderColor(), cra, sheet, workbook);
        RegionUtil.setRightBorderColor(style.getRightBorderColor(), cra, sheet, workbook);
        RegionUtil.setLeftBorderColor(style.getLeftBorderColor(), cra, sheet, workbook);
		
	}
}
